const path = require("path");
const fs = require("fs");
const axios = require("axios");

const getAllLessons = require("./types");

const [groups, lessons] = getAllLessons();

const workDir = path.join(__dirname, "lessons");
if (!fs.existsSync(workDir)) {
  fs.mkdirSync(workDir);
}
const baseUrl = "https://www.phonics.com/assets/LETTER/soundcard_ss_images/lessonXXX_con_LETTER_cardNUM.TYPE";

async function downloadLetterResources() {
  for (let i = 0; i < groups.length; i++) {
    const group = groups[i];
    const groupID = group.groupID;
    console.log(`-Group : ${group.groupName}`);
    const groupDir = path.join(workDir, group.groupName);
    if (!fs.existsSync(groupDir)) {
      fs.mkdirSync(groupDir);
    }
    for (let j = 0; j < lessons.length; j++) {
      const lesson = lessons[j];
      if (groupID !== lesson.groupID) continue;
      const lessonName = lesson.lessonName;
      console.log(`--Lesson : ${lessonName}`);
      const lessonDir = path.join(groupDir, lessonName);
      if (!fs.existsSync(lessonDir)) {
        fs.mkdirSync(lessonDir);
      }

      for (let p = 1; p <= 9; p++) {
        const pageDir = path.join(lessonDir, `0${p}`);
        if (!fs.existsSync(pageDir)) {
          fs.mkdirSync(pageDir);
        }
        const targetJPGFile = path.join(pageDir, `${p}.jpg`);
        const targetMP3File = path.join(pageDir, `${p}.mp3`);
        if (fs.existsSync(targetJPGFile) && fs.existsSync(targetMP3File)) {
          console.log(`---${targetJPGFile} jpg/mp3已存在，跳过...`);
          continue;
        }
        let url = baseUrl.replaceAll("LETTER", lessonName);
        url = url.replace("XXX", groupID);
        url = url.replace("NUM", p);
        if(group.groupName === 'Lesson 2'){
            url = url.replace("con", "sv");
        }
        if(group.groupName === 'Lesson 4'){
            url = url.replace("con", "lv");
            url = url.replace("assets/", 'assets/long-vowels/');
        }
        if(group.groupName === 'Lesson 7'){
            url = url.replace("con", "vt")
        }
        const urlJPG = url.replace("TYPE", "jpg");
        console.log(`---${urlJPG} 开始下载`);
        await downloadFile(urlJPG, targetJPGFile);
        url = url.replace("_images", "_audio");
        const urlMP3 = url.replace("TYPE", "mp3");
        console.log(`---${urlMP3} 开始下载`);
        await downloadFile(urlMP3, targetMP3File);
      }
    }
  }
}

async function downloadFile(url, output) {
  // 如果目标文件存在，且大小大于0，则跳过
  if (fs.existsSync(output) && fs.statSync(output).size > 0) {
    console.log(`  ---> Skipped ${url}`);
    return;
  }
  try {
    // 等待一秒钟再下载
    console.log(`  -- wait 5s start ...`)
    await new Promise(resolve => setTimeout(resolve, 5000));
    console.log(`  -- wait 5s end ...`)
    const response = await fetch(url);
    // console.log(response);
    const buffer = await response.arrayBuffer();
    if (buffer.byteLength === 0) throw new Error(`下载失败：size:${buffer.byteLength},status:${response.status}`);
    fs.writeFileSync(output, Buffer.from(buffer));
  } catch (e) {
    console.log(" ❌️error occured,continue", e);
    // downloadLetterResources();
    // process.exit(1);
  }
}

downloadLetterResources();
